//Requires prototype, proto.menu, 

document.observe('dom:loaded', initMemonaut);
window.onbeforeunload = promptForSave;

var gxCurrentScrap = null;
var gxClipboard = null;

var gsDocTitle="";
var gsDocFilename="";

var gxDragger=null;
var gaxSelection = null;
var gasFormatBrush = null;
var gaxLastDeleted = null;

if(!gasNotebooks)
    var gasNotebooks = [];

var gbDirty = false;
var gnIconMax = 12;
var gnIconMin = 1;

var gxTwitter = null;
var gxTransfer = null;

function initMemonaut() {
    Model_init();
    View_init();
    Controller_init();
    StatusBar_clear(); //For OK, startup prompt
}

function about() 
{
    alert('Memonaut Brainstormer Notebook\nVersion 1.30 (C) 2010 The Oraclique \nDeveloped by SonOfDelphi\nhttp://memonaut.googlecode.com/');
}

function Scrap_toggleFold(elmt)
{
    var target = elmt;

    if(!target.down('.commentlist'))
            return;

    if(!target.hasClassName('minimized')){
            foldNote(target);
            displayStatus('Folded note.');
    }
    else {
            expandNote(target);
            displayStatus('Expanded note.');
    }

}

function Scrap_createWithWrapper(text)
{
    var wrapper = document.createElement('li');
    wrapper.addClassName('wrapper');

    var scrap = document.createElement('div');
    scrap.addClassName('scrap');

    var info   = document.createElement('span');
    info.addClassName('info');

    var currentTime = new Date();
    var month = currentTime.getMonth() + 1;month= month>9? month:'0'+month;
    var day = currentTime.getDate();day= day>9? day:'0'+day;
    var year = currentTime.getFullYear();
    var hours = currentTime.getHours(); hours= hours>9? hours:'0'+hours;
    var minutes = currentTime.getMinutes();minutes= minutes>9? minutes:'0'+minutes;
    var seconds = currentTime.getSeconds();seconds= seconds>9? seconds:'0'+seconds;

    var infoText = 'Added at ' + hours + ':' + minutes + ':' + seconds+ ' on '+  year + '-' + month + '-' + day  ;
    info.insert({top:document.createElement('br')});
    info.insert({bottom:infoText});

    var content = document.createElement('div');
    content.addClassName('content');
    content.insert(text);

    scrap.insert({bottom:content});
    scrap.insert({bottom:info});

    wrapper.insert({bottom:scrap});
    return wrapper;
}

function getAddLocation()
{
    var location = $('Scrapbook');

    if(gbAddMode == "eCurrentScrapAfter")
        location = gxCurrentScrap ? gxCurrentScrap.up('.wrapper'): location;
    else if(gbAddMode == "eCurrentScrapInto"){
        if(gxCurrentScrap){
            location = Scrap_getCommentList(gxCurrentScrap.up('.wrapper'));
        }
    }
    return location;
}

function addScrap(idSourceInput)
{
    var text= $F($(idSourceInput));
    text = text.replace(/&/g, "&amp;").replace(/</g,"&lt;").replace(/>/g, "&gt;");
    text = text.replace(/\n/g,"<br>");

    var eAddMode = gbAddMode;
    if(!gxCurrentScrap) eAddMode = "eScrapbookTop";

    if(text.blank()){
            $(idSourceInput).value="Enter some text to add!";
            $(idSourceInput).removeClassName('editing');
            return;
    }

    if(eAddMode == "eCurrentScrapEdit"){
        var bFailure = replaceCurrentScrap(text);
        if(!bFailure)
            return;
    }

    var wrapper=Scrap_createWithWrapper(text);
    var addToLocation = getAddLocation();
    var scrollToLocation = wrapper;

    switch(eAddMode)
    {
       case "eScrapbookTop":
            addToLocation.insert({top:wrapper});
            break;

        case "eCurrentScrapAfter":
             if(gxCurrentScrap) addToLocation.insert({after:wrapper});
             else addToLocation.insert({top:wrapper});
           break;

        case "eCurrentScrapInto":
             if(gxCurrentScrap) addToLocation.insert({bottom:wrapper});
             else addToLocation.insert({top:wrapper});
           break;

        case "eCurrentScrapEdit":
             if(!gxCurrentScrap) addToLocation.insert({top:wrapper});
             break;

        case "eScrapbookLast":
             addToLocation.insert({bottom:wrapper});
           break;
    }

    Scrap_activateWrapper(wrapper);
    gxMenuClip.refresh();
    gxMenuCommentList.refresh();
    gxMenuScrap.refresh();

    intelliScroll(scrollToLocation);
    if(eAddMode != "eCurrentScrapInto")
        CurrentScrap_setNew(wrapper.down('.scrap'), true);

    displayStatus('Added note.');
    flagDirty();
}

function saveFile(bNoPrompt)
{
    if(!isSaveAllowed()){
       return;
    }

    displayStatus('Saving notebook...');

    if($('DocFilename').options.is_empty){
         displayStatus("Please enter a filename.");
         $('DocFilename').innerHTML = getCurrentFilename();
         $('DocFilename').edit();
        return;
    }

    var saveFilename = $('DocFilename').innerHTML;
    removeUIForSave(); //TODO: Better is to filter the view elements out

    if(!isNewFilename(getCurrentFilename(), saveFilename)){
         saveNotebookList();
         displayStatus(saveCurrentFile());
         flagClean(); //TODO: Check for success
         restoreUI();
         return 0;
    }

    if(!bNoPrompt)
        if(!confirm("Save to file " + saveFilename + "?")){
            displayStatus("File not saved.");
            restoreUI(); //TODO: Above 
            return;
        }

    if(saveFilename.lastIndexOf(".html") <= 0)
        saveFilename = saveFilename +".html";

    displayStatus(saveFileAs(saveFilename));
    flagClean(); //TODO: Check for success

    restoreUI();//TODO: Above 
}

function NotePod_onClick (element)
{
    if(!element.hasClassName('editing')){
            element.select();
            element.addClassName('editing');
            if(gbAddMode!="eCurrentScrapEdit"){
                element.value = '';
                NotePod_refresh();
            }
    }
}

function Scrap_info(elmt)
{
    var target = elmt.up('.wrapper').down('.scrap');
    target = target.down('.info');
    if(target.visible())
            target.hide();
    else
            target.show();
}

function Bookmark_activate(elmt)
{
    var target = elmt;

    new Proto.EIP( {
            type: 'text',
            item: target,
            save_url: 'edit.php',
            postSave: flagDirty,
            is_wrapped:true
    } );

    target.observe('click', Bookmark_scrollTo);

    var button = document.createElement('img');
    button.setAttribute('src', gsResDir + 'bookmark.png');
    button.setAttribute('class', 'iconBookmark');
    button.setAttribute('title', 'Click for menu.');

    target.insert({before:button});
}

function Scrap_bookmark(elmt)
{
    var target = elmt.up('.wrapper').down('.scrap');
    target = target.down('.content');

    var location = target.identify();
    var addToLocation=$('listBookmarks');

    var bookmark = document.createElement('a');
    bookmark.addClassName('bookmark');

    var item = document.createElement('li');

    bookmark.setAttribute('href', "#"+ target.id);
    var text = Prototype.Browser.IE? target.innerText:target.textContent;
    text = (text.length > 20)? text.substring(0,19): text;
    bookmark.insert(text);
    item.insert({top:bookmark});
    addToLocation.insert({top:item});

    Bookmark_activate(bookmark);
    gxMenuBookmarks.refresh();
    flagDirty();
}

function CurrentScrap_getNew(scrapElement)
{
    var cursor = scrapElement.up('.wrapper');
    var check = null;

    check = cursor.next('.wrapper');
    if(check){
        return check.down('.scrap');
    }
    
    check = cursor.previous('.wrapper')
    if(check) {
        return check.down('.scrap');
    }
    
    check = cursor.up('.wrapper');
    if(check){
        return check.down('.scrap');
    }

    return null;
}

function Scrap_delete(elmt, bNoPrompt, bIsEmpty)
{
    if(!bNoPrompt)
        if(!confirm("Delete note(s) and all its sub-notes?")){
            return;
        }
    var target =  elmt.up('.wrapper');

    var currentCheck = target.down('.scrap');
    if(currentCheck){
            if(currentCheck.hasClassName('current')){
                    var result = CurrentScrap_getNew(gxCurrentScrap);
                    CurrentScrap_setNew(result, true);
            }

    }

    var parent = target.up('.wrapper');
    var prev = target.previous('.wrapper');
    
    target.remove();
    if(parent) removeCommentListIfEmpty(parent);
    if(!bIsEmpty) {
        //Store parameters for rudimentary undo delete
        gaxLastDeleted =[];
        gaxLastDeleted.push(parent);
        gaxLastDeleted.push(prev);
        gaxLastDeleted.push(target);
        $('undeleter').show();

        flagDirty();
        displayStatus('Deleted note(s).');
    }
}

function Scrap_restore(){
    if(!gaxLastDeleted) return;

    var note = gaxLastDeleted.pop();
    var previous = gaxLastDeleted.pop();
    var parent = gaxLastDeleted.pop();
    gaxLastDeleted = null;
    $('undeleter').toggle();

    if(previous){
        previous.insert({after:note});
    }
    else{
        if(parent){
            parent.insert({after:note});
        }
        else {
            $('Scrapbook').insert({top:note});
        }
    }
    CurrentScrap_setNew(note.down('.scrap'), true);
    
}

function Scrap_move(elmt, moveUp)
{
    var swapitem = elmt.up('.wrapper');
    var swapper = moveUp ? swapitem.previous('.wrapper'): swapitem.next('.wrapper');

    if (swapper){
            Scrap_swap(swapitem, swapper);
            displayStatus('Shifted note.');
    }
    else displayStatus('Cannot move further.');
    flagDirty();
}

function Scrap_swap(swapitem, swapper)
{
    if(swapitem==swapper)
        return;
    var bCurrentScrap=false;
    if(swapitem.down('.scrap').hasClassName('current')){
            CurrentScrap_reset();
            bCurrentScrap = true;
        }

    var temp = swapper.cloneNode(false); // no need to clone deep
    Element.replace(swapitem, temp);
    Element.replace(swapper, swapitem);
    Element.replace(temp, swapper); // make sure references (like event observers) are kept

    flagDirty();
    if(bCurrentScrap)
        CurrentScrap_setNew(swapitem.down('.scrap'), true);
}

function Scrap_shiftOut(elmt)
{
    var target = elmt.up('.wrapper');
    var check = target.up('.wrapper');
    if(!check){
            displayStatus('Already at top level.');
            return;
    }

    if(target.down('.scrap').hasClassName('current'))
        CurrentScrap_reset();

    check.insert({after:target});
    removeCommentListIfEmpty(check);
    
    gxMenuClip.refresh();
    gxMenuCommentList.refresh();
    gxMenuScrap.refresh();

    displayStatus('Shifted note.');
    flagDirty();
    CurrentScrap_setNew(target.down('.scrap'),true);
}

function Scrap_shiftIntoPrevious(elmt)
{
    var target = elmt.up('.wrapper');
    var check = target.previous('.wrapper');
    if(!check){
            displayStatus('No previous note to move into.');
            return;
    }

    if(target.down('.scrap').hasClassName('current'))
        CurrentScrap_reset();
    check = Scrap_getCommentList(check);
    check.insert({bottom:target});

    gxMenuClip.refresh();
    gxMenuCommentList.refresh();
    gxMenuScrap.refresh();

    displayStatus('Shifted note.');
    flagDirty();
    CurrentScrap_setNew(target.down('.scrap'),true);
}

function Scrap_shiftIntoNext(elmt)
{
    var target = elmt.up('.wrapper');
    var check = target.next('.wrapper');
    if(!check){
            displayStatus('No next note to move into.');
            return;
    }
    
    if(target.down('.scrap').hasClassName('current'))
        CurrentScrap_reset();

    check = Scrap_getCommentList(check);
    check.insert({top:target});
    removeCommentListIfEmpty(check);
    gxMenuClip.refresh();
    gxMenuCommentList.refresh();
    gxMenuScrap.refresh();

    displayStatus('Shifted note.');
    flagDirty();
    CurrentScrap_setNew(target.down('.scrap'),true);
}

function dummy()
{
    alert("Not implemented yet!");
}

function Scrap_addNote(elmt, bSameLevel, bPrevious)
{
    var target = elmt.up('.wrapper'); // .down('.scrap');

    var note = Scrap_createWithWrapper('');
    if(!bSameLevel){
        var commentList = Scrap_getCommentList(target);
        commentList.insert({bottom:note});
    }
    else{
        bPrevious? target.insert({before:note}): target.insert({after:note});
    }

    activateNewNote(note,target);
}

function Scrap_addFreeNote(bAtBottom){
    if(bAtBottom){
        var note = Scrap_createWithWrapper('');
        $('Scrapbook').insert({bottom:note});
    }
    activateNewNote(note, note);
}

function activateNewNote(note, scrollTo){
    CurrentScrap_setNew(note.down('.scrap'), false)
    note.show();
    intelliScroll(scrollTo);

    Scrap_activateWrapper(note, true);
    gxMenuClip.refresh();
    gxMenuCommentList.refresh();
    gxMenuScrap.refresh();

    displayStatus('Adding note.');
}

function Scrap_getCommentList(wrapper, bDontCreate)
{
    var target = wrapper;
    target = target.down('.scrap');

    var commentList =  target.down('ol');
    if(!commentList){
            if(bDontCreate) return null;
            commentList = document.createElement('ol');
            commentList.addClassName('commentlist');
            target.insert({bottom:commentList});
            var icon = viewCreateCommentList();
            target.insert({before:icon});
            icon.observe('contextmenu', CommentList_cycleNumbering );
            gxMenuCommentList.refresh();
    }

    if(!commentList.visible())
            Scrap_toggleFold(target);

    return commentList;
}

function setCurrentScrap(ev)
{
    var target = ev.target.up('.wrapper').down('.scrap');
    CurrentScrap_setNew(target, true);
}

function CurrentScrap_reset()
{
    if(!gxCurrentScrap)
            return;
    View_unmakeScrapCurrent();
    gxCurrentScrap.removeClassName('current');
    gxCurrentScrap.down('.content').removeAttribute('contenteditable');
    gxCurrentScrap = null;
}

function CurrentScrap_setNew(element, bScrollTo)
{
    CurrentScrap_reset();
    if(element == null) return;

    if(!element.visible()) element.show();
    View_makeScrapCurrent(element);
    element.addClassName('current');
    gxCurrentScrap = element;

    if(bScrollTo){
        var father = gxCurrentScrap.up('.wrapper').up('.wrapper')
        if(father) intelliScroll(father); else intelliScroll(gxCurrentScrap);
    }

    var content = gxCurrentScrap.down('.content');
    if(content) content.setAttribute("contenteditable", true);

    NotePod_refresh();
}

function removeUIForSave()
{
    $$('.protomenu').each(function (elmt){elmt.remove();});
    $$('.view').each(function(elmt){elmt.remove();});
    $$('.iconBookmark').each(function(elmt){elmt.remove();});
    $$('.selection').each(function(elmt){elmt.removeClassName('selection');});
    $$('.clipboard').each(function(elmt){elmt.removeClassName('clipboard')();});

    NotebookList_clear();
}

function restoreUI()
{
    initDocumentElements();
    initMenuMemonaut();
}

function checkForEdits()
{
    var isEditInProgress = $$('.eip_editing');
    if(isEditInProgress.length > 0)
        return true;
    return false;
}

function changeAddMode(elmt)
{
    gbAddMode = elmt.options[elmt.selectedIndex].value;
    if(gbAddMode=="eCurrentScrapEdit"){
        if(gxCurrentScrap){
            NotePod_refresh();
            $('textareaScrap').focus();
        }
    }
}

function Bookmark_move(elmt, moveUp)
{
    var swapitem = elmt;
    var swappers = moveUp ? swapitem.previousSiblings(): swapitem.nextSiblings();

    if (swappers.length > 0){
            var swapper = swappers[0];
            Bookmark_swap(swapitem, swapper);
    }
}

function Bookmark_swap(swapitem, swapper)
{
    if( (swapitem.down('.eip_editing')) || (swapper.down('.eip_editing'))){
            displayStatus("Please complete your edit before moving.");
            return;
    }

    var temp = swapper.cloneNode(false); // no need to clone deep
    Element.replace(swapitem, temp);
    Element.replace(swapper, swapitem);
    Element.replace(temp, swapper); // make sure references (like event observers) are kept

    gxMenuBookmarks.refresh();
}

function AddNote_onClick(elmt)
{
    addScrap('textareaScrap');
    $('textareaScrap').value="What's on your mind?";
    $('textareaScrap').removeClassName('editing');
    NotePod_refresh();
}


function Scrap_edit(elmt){
    var target = elmt.up('.wrapper').down('.scrap').down('.content');
    target.edit();
    displayStatus('Editing note.');
    flagDirty();
}

function CurrentScrap_edit(){
    if(!gxCurrentScrap) return;
    Scrap_edit(gxCurrentScrap);
}

function CurrentScrap_info(){
    if(!gxCurrentScrap) return;
    Scrap_info(gxCurrentScrap);
}

function CurrentScrap_bookmark(){
    if(!gxCurrentScrap) return;
    Scrap_bookmark(gxCurrentScrap);
}

function Scrap_copy(elmt){
    dummy();
}

function CurrentScrap_copy(){
    if(!gxCurrentScrap) return;
    Scrap_cut(gxCurrentScrap);
}

function CurrentScrap_cut(){
    if(!gxCurrentScrap) return;
    Scrap_cut(gxCurrentScrap);
}

function CurrentScrap_paste(){
    if(!gxCurrentScrap) return;
    Scrap_paste(gxCurrentScrap);
}

function Scrap_cut(elmt)
{
    if(gxClipboard){
        gxClipboard.removeClassName('clipboard');
    }
    var target = elmt.up('.wrapper');
    
    gxClipboard = target;
    gxClipboard.addClassName('clipboard');
    displayStatus('Content moved to clipboard.');
    flagDirty();
}

function Scrap_paste(elmt)
{
    if(!gxClipboard)
        return;

    var target = elmt.up('.wrapper');
    var parent = gxClipboard.up('.wrapper');
    target.insert({after:gxClipboard});

    if(parent)
        removeCommentListIfEmpty(parent);

    CurrentScrap_setNew(gxClipboard.down('.scrap'), true);
    gxClipboard.removeClassName('clipboard');
    gxClipboard = null;
    displayStatus('Pasted note.');
    flagDirty();
}
var gxStatusBarTimeout = null;

function StatusBar_show(msg)
{
    $('StatusText').innerHTML =  '<center>' + msg + '</center>';
    if(gxStatusBarTimeout) clearTimeout(gxStatusBarTimeout);
    gxStatusBarTimeout = setTimeout ( "StatusBar_clear()", 3500 );
}

function StatusBar_clear()
{
    $('StatusText').innerHTML = '<center>OK.</center>';
    gxStatusBarTimeout = null;
}

function displayStatus(msg)
{
    StatusBar_show(msg);
}

function titleChange(newTitle)
{
    document.title = newTitle;
    flagDirty();
}

function isNewFilename(oldname, newname)
{
    //Removes the extension .html
    var extensionPos = newname.lastIndexOf(".html");
    if(extensionPos > 0){
        newname = newname.substring(0, extensionPos).toLowerCase();
    }

    extensionPos = oldname.lastIndexOf(".html");
    if(extensionPos > 0){
        oldname = oldname.substring(0, extensionPos).toLowerCase();
    }

    if(oldname == newname)
        return false;
    return true;
}
function fileChange(newname, oldname)
{
    if(!isNewFilename(oldname, newname))
        return oldname;

    flagDirty();
    if(newname.lastIndexOf(".html") <0)
        newname = newname + '.html';
    
    if(confirm("Save this file as "+ newname + " now?")){
            if(!isSaveAllowed())
                return newname + '.html';
            
            saveFile(true);
        }
    return newname;
}

function removeExtension(filename)
{
        var extensionPos = filename.lastIndexOf(".html");
        if(extensionPos > 0)
            return filename.substring(0, extensionPos);
        return filename;
}

function isSaveAllowed()
{
    if(checkForEdits()){
        displayStatus("Please complete your edits before you save.");
        return false;
    }

    if(!(Prototype.Browser.Gecko | Prototype.Browser.IE)){
        displayStatus("Save not supported for your browser. Firefox-, Internet Explorer- only.");
        return false;
    }

    return true;
}

function newFile(bNoPrompt)
{
    if(!bNoPrompt){
        if(gbDirty)
            if(!confirm("Clear current content? Press Cancel to go back and save current file."))
            return;
    }

    $('DocFilename').innerHTML = 'unnamed.html';
    $('Scrapbook').innerHTML = '';
    $('listBookmarks').innerHTML = '';
    $('DocTitle').innerHTML = 'Untitled Notebook';
    document.title = 'Untitled Notebook';
    gxCurrentScrap = null;

    var starterScrap = Scrap_createWithWrapper('Fill me up!');
    $('Scrapbook').insert({top:starterScrap});
    Scrap_activateWrapper(starterScrap);
    CurrentScrap_setNew(starterScrap.down('.scrap'));
    gxMenuClip.refresh();
    gxMenuCommentList.refresh();
    gxMenuScrap.refresh();

    displayStatus('New notebook ready.');
    $('DocFilename').edit();
    flagDirty();
}

function exportView()
{
    createExport($('Notebook'));
}

function createExport(elmt)
{
    var target = window.open();
    target.title = 'Memonaut - Exported View';
    target.document.open();
    target.document.write('<!DOCTYPE html PUBLIC"-// W3C//DTD XHTML 1.0 Transitional//EN"" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
        + '<html><head><title>Memonaut - Exported View</title>'
        + '<link rel="stylesheet" type="text/css" href="' + gsAppDir + 'snapshot.css" />'
        + '<script type="text/javascript" src="' + gsAppDir + 'prototype.js"> </script>'
        + '<script type="text/javascript" src="' + gsAppDir + 'snapshot.js"> </script>'
        + '</head><body><div id="Notebook">');
    target.document.write(elmt.innerHTML);
    target.document.write("</div></body></html>");
    target.document.close();
}

function restoreArea(elmt){
    var target = elmt.up('.area').down('.areacontent');

    if(target){
        if(!target.hasClassName('barified')) {
            barifyArea(target);
        }
        else {
            unbarifyArea(target);
        }
    }
}

function barifyArea(areacontent){
    var target = areacontent.up('.area').down('.areacontent');
    if(target){
            target.addClassName('barified');
            target.up(0).setStyle({height:'2em'});
            target.hide();
    }
}

function unbarifyArea(areacontent){
    var target = areacontent.up('.area').down('.areacontent');
    target.show();
    target.up(0).setStyle({height:''});
    target.removeClassName('barified');
}

function intelliScroll(wrapper, bShowFull){
    var elmt = bShowFull? wrapper: wrapper.down('.content');
    var vpDim = document.viewport.getDimensions();
    var vpOff = document.viewport.getScrollOffsets();
    var elmtHeight = elmt.getHeight();
    var elmtOffset = elmt.cumulativeOffset();
    var bScroll = false;
    
    if (elmtOffset.top >= vpOff.top){
        if((elmtOffset.top + elmtHeight) <= (vpOff.top + vpDim.height)){
            return;
        }
    }
    elmt.scrollTo();
}

function Note_export(elmt){
   createExport(elmt);
}

function NotebookList_add(filename)
{
    gasNotebooks.unshift(filename);
}

function saveNotebookList()
{
    var content = 'var gasNotebooks = ' + gasNotebooks.toJSON() + ';';
    saveNewFile(gsAppDir +'notebooks.js', content);
}

function NotebookList_clear()
{
    $('listNotebooks').innerHTML='';
}

function Scrap_join(source, target)
{
    var targetText = Scrap_getContent(target,true);
    var sourceText = Scrap_getContent(source,true);

    source = source.down('.scrap').down('.content');
    target = target.down('.scrap').down('.content');

    if(source.empty()){
        displayStatus("No content to merge!");
        return 1;
    }

    if(source.hasClassName('current')){
        CurrentScrap_reset();
    }
    var parent = source.up('.wrapper');

    var mergedText =  targetText + '<br>' + sourceText;
    target.innerHTML = mergedText;
    source.innerHTML = '';

    CurrentScrap_setNew(target,true);
    if(parent) removeCommentListIfEmpty(parent);
    var sourceCommentList = source.up('.scrap').down('.commentlist');
    var targetCommentList = null;
    target=target.up('.wrapper');

    if(sourceCommentList){
        targetCommentList = Scrap_getCommentList(target);

        var sourceChildren = sourceCommentList.getElementsBySelector('li');
        for(var i=0;i<sourceChildren.length; i++)
            targetCommentList.insert({bottom:sourceChildren[i]});
    }

    source.up('.wrapper').remove();
    flagDirty();
}

function Scrap_getContent(wrapper, bHTML)
{
    var target = wrapper.down('.scrap').down('.content');
    var text = '';
    text = bHTML? target.innerHTML:(Prototype.Browser.IE? target.innerText:target.textContent);
    return text;
}

function Scrap_merge(elmt, moveUp)
{
    var swapitem = elmt.up('.wrapper');
    var swapper = moveUp ? swapitem.previous('.wrapper'): swapitem.next('.wrapper');

    if (swapper){
            if(!Scrap_join(swapitem, swapper))
                displayStatus('Merged note.');
    }
    else displayStatus('No note to merge into.');
}

function toggleHelp()
{
    var target=$('Help');
    if(target)
        target.toggle();
}

function Scrap_mergeParent(elmt)
{
    var source = elmt.up('.wrapper');
    var target = source.up('.wrapper');

    if (target){
            if(!Scrap_join(source, target)){
                removeCommentListIfEmpty(target);
                displayStatus('Merged note.');
            }
    }
    else displayStatus('No note to merge into.');

}

function Notebook_move(elmt, moveUp)
{
    var swapitem = elmt;
    var swappers = moveUp ? swapitem.previousSiblings(): swapitem.nextSiblings();

    if (swappers.length > 0){
            var swapper = swappers[0];
            Notebook_swap(swapitem, swapper);
            gxMenuNotebookList.refresh();
            NotebookList_refresh();
    }
}

function Notebook_swap(swapitem, swapper)
{
    //This is OK only because there are no child elements. Otherwise handlers lost...
    var itemtext = swapper.innerHTML;
    swapper.innerHTML = swapitem.innerHTML;
    swapitem.innerHTML = itemtext;
}

function NotebookList_refresh()
{
    gasNotebooks = [];

    var displistNotebook = $$('#listNotebooks li a');
    for(var i=0; i< displistNotebook.length; i++){
        var notebook = displistNotebook[i];
        var name = Prototype.Browser.IE? notebook.innerText:  notebook.textContent;
        gasNotebooks.push(name);
    }
}

function flagDirty()
{
    gbDirty = true;
    $('SaveNotice').innerHTML = "*";
}

function flagClean(){
    $('SaveNotice').innerHTML = "";
    gbDirty = false;
}

function promptForSave(){
    removeUIForSave(); //TODO: Better is to filter the view elements out
    if(localStorage)
        localStorage.setItem('memonaut', $('Scrapbook').innerHTML);

/*    if(gbDirty)
        return "You might have unsaved changes! Press Cancel to go back and save your changes."; 
*/
}

function Scrap_clone(elmt){
    var target = elmt.up('.wrapper').down('.scrap').down('.content');
    var text = Prototype.Browser.IE? target.innerText:target.textContent;
    var note = Scrap_createWithWrapper(text);
    target=target.up('.wrapper');

    if(target.down('.scrap').hasClassName('current'))
        CurrentScrap_reset();

    target.insert({before:note});
    CurrentScrap_setNew(target.down('.scrap'),true);
    Scrap_activateWrapper(note);
    gxMenuClip.refresh();
    gxMenuCommentList.refresh();
    gxMenuScrap.refresh();
    displayStatus('Cloned note content.');
    flagDirty();
}

function removeCommentListIfEmpty(elmt)
{
    var xCommentList = elmt.down('.commentlist');
    if(!xCommentList) return;
    if(xCommentList.getElementsByTagName('li').length>0) return;

    xCommentList.remove();
    elmt.down('.foldindicator').remove();
}

function removeCommentList(wrapper)
{
    var xCommentList = wrapper.down('.commentlist');
    if(!xCommentList) return;
    xCommentList.remove();
    wrapper.down('.foldindicator').remove();
}

function detachCommentList(wrapper)
{
    var xCommentList = wrapper.down('.commentlist');
    if(!xCommentList) return;
    var aNotesInList = xCommentList.immediateDescendants();
    var note = null;
    
    for(var i=aNotesInList.length;i>0;i--){
        note = aNotesInList[i-1];
        wrapper.insert({after:note});
    }
    xCommentList.remove();
    wrapper.down('.foldindicator').remove();
    
    gxMenuClip.refresh();
    gxMenuCommentList.refresh();
    gxMenuScrap.refresh();
    displayStatus('Detached notes from list.');
    flagDirty();
}

function selectCommentList(wrapper)
{
    Selection_clear();
    var xCommentList = wrapper.down('.commentlist');
    if(!xCommentList) return;
    var aNotesInList = xCommentList.immediateDescendants();
    var note = null;

    for(var i=aNotesInList.length;i>0;i--){
        note = aNotesInList[i-1];
        Selection_toggle(note);
    }
}

function Notes_interleave(list, size, depth){
    var looper = 0, swapindex=0;
    for(looper=0;looper < size; looper+=depth){
        swapindex = looper % depth;
        Scrap_swap(list[looper], list[swapindex]);
        }
}

function Notes_shuffle(list){
    //Interleaved Shuffle Deck algorithm
    var test = list.immediateDescendants();
    var notes = [];

    for(looper=0;looper<test.length;looper++){
        if(test[looper].hasClassName('wrapper'))
            notes.push(test[looper]);
    }

    var cardinal = notes.length, looper=0, swapperindex=0, swapindex=0;

    Notes_interleave(notes, cardinal, 2);
    for(looper=0; looper< (cardinal/3); looper++){
        swapperindex = Math.floor((Math.random()*12509))%(cardinal);
        swapindex = Math.floor((Math.random()*79123))%(cardinal);
        Scrap_swap(notes[swapperindex], notes[swapindex]);
    }
}

function Scrap_addIcon(elmt){
    var target = elmt.up('.wrapper').down('.scrap');
    var imageAttacher = Scrap_getAttachIcons(target);
    var img = document.createElement('img');
    img.setAttribute('src', gsIcoDir + gnIconMin + '.png');
    imageAttacher.insert({bottom:img});
    activateIcon(img);
    gxMenuAttachIcon.refresh();
    displayStatus('Added icon.');
    flagDirty();
}

function Scrap_cycleIcon(icon, bBackward){
    var name = icon.getAttribute('src');
    name = name.replace(gsAppDir+'icons/','');
    name = name.replace('.png','');
    name = name - 0;
    if(!bBackward) {
        name = (name<gnIconMax)? (name+1): gnIconMin;
    }
    else{
        name = (name > gnIconMin) ? (name-1): gnIconMax;
    }
    icon.setAttribute('src', gsIcoDir + name+'.png');
}

function Scrap_getLastIcon(scrap){
    var iconList = Scrap_getAttachIcons(scrap, true);
    if(!iconList) return null;
    var icon = iconList.down('.attachicon');
    var check = icon.next('.attachicon')
    while(check){
        icon = icon.next('.attachicon');
        check = check.next('.attachicon');
    }
    return icon;
}

function Scrap_removeIcon(icon){
    if((!icon.next('.attachicon')) && (!icon.previous('.attachicon'))){
        icon.up('.attachicons').remove();
        return;
    }
    icon.remove();
}

function AttachIcon_swap(swapitem, swapper){
    if((swapitem == null)|| (swapper==null)) return;
    if(swapitem==swapper) return;

    var temp = swapper.cloneNode(false); // no need to clone deep
    Element.replace(swapitem, temp);
    Element.replace(swapper, swapitem);
    Element.replace(temp, swapper); // make sure references (like event observers) are kept

    flagDirty();
}

function replaceCurrentScrap(text){
    if(!gxCurrentScrap) return true;
    var contentHolder = gxCurrentScrap.down('.content');
    contentHolder.innerHTML = text;
    return false;
}

function Scrap_tweet(wrapper){
    var content = escape(Scrap_getContent(wrapper));
    var twitterPostURL = "http://twitter.com/home?status=";

    gxTwitter = window.open(twitterPostURL+content);
}

function Scrap_color(wrapper){
    var content = wrapper.down('.content');

    if(content.hasClassName('red'))
        {content.removeClassName('red');       content.addClassName('green');    return;}
    if(content.hasClassName('green'))
        {content.removeClassName('green');    content.addClassName('blue');    return;}
    if(content.hasClassName('blue'))
        {content.removeClassName('blue');    return;}

    content.addClassName('red');
}

function Scrap_copyFormatting(wrapper){
    var content = wrapper.down('.content');
    var formatting = content.getAttribute('class');

    gasFormatBrush = [];
    formatting = formatting.split(/ /ig);
    for(var i=0;i<formatting.length;i++){
        if(isFormatting(formatting[i]))
            gasFormatBrush.push(formatting[i]); //Splice is how you remove elements from an array
    }
    displayStatus('Copied formatting.');
}

function Scrap_pasteFormatting(wrapper, bDontClear){
    var content = wrapper.down('.content');
    var formatting = content.getAttribute('class');
    
     //Remove all formatting
    formatting = formatting.split(/ /ig);
    for(var i=0;i<formatting.length;i++){
        if(isFormatting(formatting[i]))
            content.removeClassName(formatting[i]); //Splice is how you remove elements from an array
    }

    //Apply new formatting
    for(var i=0;i<gasFormatBrush.length;i++)
        content.addClassName(gasFormatBrush[i]);

    if(!bDontClear)
        gasFormatBrush = null;
    displayStatus('Applied formatting.');
    return;
}

function FormatPainter_apply(){
    if(!gasFormatBrush){
        CurrentScrap_copyFormatting();
        return;
    }

    Selection_update();
    if(!gaxSelection){
        CurrentScrap_pasteFormatting();
        return;
    }

    var source = gaxSelection;
    for(var i=0;i<source.length;i++){
        Scrap_pasteFormatting(source[i], true);
    }
    gasFormatBrush = null;
}

function CurrentScrap_copyFormatting(){
    if(!gxCurrentScrap) return;
    Scrap_copyFormatting(gxCurrentScrap.up('.wrapper'));
}

function CurrentScrap_pasteFormatting(){
    if(!gxCurrentScrap) return;
    Scrap_pasteFormatting(gxCurrentScrap.up('.wrapper'), true);
}

function isFormatting(classname){
    switch(classname){
        case 'red':
        case 'green':
        case 'blue':
        case 'bold':
        case 'underline':
        case 'strikethrough':
        case 'italic':
        case 'large':
        case 'xlarge':
        case 'xxlarge':
        case 'xsmall':
        case 'xxsmall':
            return true;
    }
    return false;
}

function lockToggleCommentList(list){
    if(!list.hasClassName('locked')){
        list.addClassName('locked');
        displayStatus('Locked list.');
    }
    else{
        list.removeClassName('locked');
        displayStatus('Unlocked list.')
    }

}

function Selection_toggle(wrapper){
    if(!Selection_contains(wrapper))
        Selection_add(wrapper);
    else
        Selection_remove(wrapper);
}

function Selection_add(wrapper){
    if(!wrapper.hasClassName('wrapper')) return;

    wrapper.addClassName('selection');
    Selection_removeChildren(wrapper);
    Selection_update();
}

function Selection_remove(wrapper, bNoUpdate){
    wrapper.removeClassName('selection');
    if(!bNoUpdate) return;
    Selection_update();
}

function Selection_clear(){
    gaxSelection = null;
    $$('.selection').each(function (elmt){
        Selection_remove(elmt);
    });
    Selection_update();
}

function Selection_contains(wrapper){
    if(wrapper.hasClassName('selection')) return true;
    if(wrapper.up('.selection')) return true;
    return false;
}

function Selection_removeChildren(wrapper){
    if(!wrapper.down('.selection')) return;
    var child = null;
    while(wrapper.down('.selection')){
        child = wrapper.down('.selection');
        Selection_remove(child, true);
    }
    Selection_update();
}

function Selection_update(){
    //Using a lazy update strategy
    gaxSelection = $$('.selection');
    if(gaxSelection.length<1)
        gaxSelection = null;
}

function Scrap_moveAbsolute(source, target, bInto){
    flagDirty();
    if(!source.length){
        Scrap_moveSingle(source, target, bInto);
        return;
    }

    for(var i=0;i<source.length;i++){
        Scrap_moveSingle(source[i], target, bInto)
    }
}

function Scrap_moveSingle(source,target,bInto){
    if(source == target)
        return false;
    if(target.descendantOf(source)){
        displayStatus('Cannot move into own subsection.');
        return false;
    }

    var current = source.down('.current');
    if(current)
        CurrentScrap_reset();

    var parent = source.up('.wrapper');
    if(!bInto){
        if(target.next('.wrapper')==source)
            target.insert({before:source});
        else
            target.insert({after:source});
    }
    else {
            var check = Scrap_getCommentList(target);
            check.insert({top:source});
    }

    if(parent)
        removeCommentListIfEmpty(parent);
    if(current)
        CurrentScrap_setNew(source.down('.scrap'), true);
    return true;

}

function cancelEdit(content, isEmpty){
    if(isEmpty){
        Scrap_delete(content, true, true);
    }
}

function addNoteToTop(selectedContent)
{
    var wrapper=Scrap_createWithWrapper(selectedContent);
    //selectedContent is the text selected in the tab
    var addToLocation= $('Scrapbook');
    // we will add by default to the top of the notebook
    addToLocation.insert({top:wrapper});

    //Making sure that all the controls,menus etc are available
    Scrap_activateWrapper(wrapper);
    gxMenuClip.refresh();
    gxMenuCommentList.refresh();
    gxMenuScrap.refresh();
    intelliScroll(wrapper);
    displayStatus('Added note.');
    flagDirty();
}

